package cn.itcast.blog.servlet;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.itcast.blog.Utils.ServiceProxyUtils;
import cn.itcast.blog.domain.Category;
import cn.itcast.blog.service.CategoryService;

@WebServlet(urlPatterns = {
		"/category/update","/category/find",
		"/category/delete","/category/add"
})
public class CategoryServlet extends BaseServlet{
	
	CategoryService categoryService = ServiceProxyUtils.cretaeProxy(new CategoryService());
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doGet(req,resp);
	}
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// TODO Auto-generated method stub
		super.doGet(req, resp);
	}
	
	//增
	public void add(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		
		Category category = new Category();
		
		//接受传过来的请求
		String name = req.getParameter("name");
		
		//解决乱码问题，这里有个小问题，用set设置不了
		String parameter = new String(name.getBytes("ISO8859-1"),"utf-8");
		
		category.setName(parameter);
		
		categoryService.insertCategory(category);
		
	}
	
	//删
	public void delete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		
		int id = Integer.valueOf(req.getParameter("id"));
		
		categoryService.deleteCategory(id);
		
		resp.setContentType("application/json;charset=utf-8");
		resp.getWriter().write("");
	}
	
	//改
	public void update(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		
		Category category = new Category();
		
		int id = Integer.valueOf(req.getParameter("id"));
		String name = req.getParameter("name");
		String priority = req.getParameter("priority");
		
		category.setId(id);
		category.setName(name);
		
		if(priority!=null) {
			int p = Integer.valueOf(priority);
			category.setPriority(p);
		}
		
		categoryService.updateCategory(category);
	}
	
	//查
	public void find(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

		List<Category> findByAll = categoryService.findByAll();
		
		writeListResponse(resp,findByAll);
	}
	
}
